package com.yeziji.config.rabbitMq;

import com.rabbitmq.client.Channel;
import com.yeziji.common.rabbitMq.RabbitMqTopicHandler;
import com.yeziji.config.EnvHolder;
import com.yeziji.utils.expansion.Str2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

/**
 * RabbitMq 监听分发器
 *
 * @author hwy
 * @since 2024/10/27 0:29
 **/
@Slf4j
public class RabbitMqListener implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        MessageProperties messageProperties = message.getMessageProperties();
        // rabbit template 发送信息，若设置了 CorrelationData 那么这里 spring 会在头部赋值
        Object fromCorrelationId = messageProperties.getHeader("spring_returned_message_correlation");
        Object toCorrelationId = messageProperties.getHeader("spring_listener_return_correlation");
        // 获取处理器
        RabbitMqTopicHandler mqTopicHandler =
                EnvHolder.getAsRabbitMqHandler(
                        messageProperties.getReceivedExchange(),
                        messageProperties.getReceivedRoutingKey()
                );
        // 通信给对应的处理器
        if (mqTopicHandler != null) {
            String body = Str2.resolveOverrideJson(new String(message.getBody()));
            // 交給模板處理消息
            log.info("[{}] accept message({} -> {}): {}", mqTopicHandler.getTopicEnum().getDesc(), fromCorrelationId, toCorrelationId, body);
            mqTopicHandler.handler(message, channel, body);
        }
    }
}
